from django.shortcuts import render

from django.conf import settings
from rest_framework.viewsets import ReadOnlyModelViewSet

from libs.random_box import RandomCooking
from . import jwt_box
from .models import JwtPool
from .serializers import JwtPoolSerializer

JWT_SECRET_KEY = settings.JWT_SECRET_KEY if settings.JWT_SECRET_KEY else 'jwt'
JWT_EXPIRE_DATE_STR = settings.JWT_EXPIRE_DATE if settings.JWT_EXPIRE_DATE else '1s'

JWT = jwt_box.JWTBox(JWT_SECRET_KEY, JWT_EXPIRE_DATE_STR)
RC = RandomCooking()


class JwtPoolViewSet(ReadOnlyModelViewSet):
    queryset = JwtPool.objects.all()
    serializer_class = JwtPoolSerializer


class JWTER:
    def create(self, data: dict, category: str) -> (int, str):
        jwtStr = JWT.jwtEncode(data)
        if not JwtPool.objects.filter(jwtStr=jwtStr).exists():
            jid = RC.salad(7)
            while JwtPool.objects.filter(jid=jid).exists():
                jid = RC.salad(7)
            jwtPool = JwtPool(
                jid=jid,
                jwtStr=jwtStr,
                category=category
            )
            jwtPool.save()
            return 0, jid
        return -1, ""
